package com.core.util;

import java.text.DecimalFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 数字操作辅助类
 * 
 * 
 */
public class NumberUtil {

	private static Log log = LogFactory.getLog(NumberUtil.class);

	/**
	 * 格式化数字，指定小数点后位数
	 * 
	 * @param number
	 * @param length
	 * @return
	 */
	public static String formatNumber(Object number, int length) {
		String ret = null;
		try {
			if (number == null) {
				return ret;
			}

			StringBuffer format = new StringBuffer("#");
			for (int i = 0; i < length; i++) {
				if (i == 0) {
					format.append(".#");
				} else {
					format.append("#");
				}
			}

			number = Double.parseDouble(number.toString());
			DecimalFormat decimalFormat = new DecimalFormat(format.toString());
			ret = decimalFormat.format(number);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	/**
	 * 格式化数字，将数字格式化为定长的字符串
	 * 
	 * @param number
	 * @param length
	 *            格式化长度
	 * @param format
	 *            格式化字符串
	 * @return
	 */
	public static String formatNumber(Object number, int length, String format) {
		String ret = null;
		try {
			format = "%" + format + length + "d";
			ret = String.format(format, number);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static String formatNumber(Object number, long length, String format) {
		String ret = null;
		try {
			format = "%" + format + length + "d";
			ret = String.format(format, number);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static void main(String[] args) {
		String s = NumberUtil.formatNumber(0, 4, "0");
		s = s.substring(0, s.length() - 1);
		s = s.replaceAll("0", "-");
		log.info(s);

	}
}
